<?php
namespace Crontab;

class Base
{

    use \CommonTrait\Base;

    private $domain = '';

    private $path = '';

    private $data = [];

    private $method = 'get';

    private $key = '';

    private $sign = 1;

    public function sendPostByCurl($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->makeData($data));
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

    public function sendGetByCurl($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "{$url}?" . $this->makeData($data));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

    public function makeData($data)
    {
        $serviceSign = $this->get(SERVICE_SIGN);
        if($this->sign){
            if(!isset($data['timestamp'])){
                $data['timestamp'] = time();
            }
            if(!isset($data['rand'])){
                $data['rand'] = mt_rand(100000, 999999);
            }
            if(empty($this->key)){
                $sign = $serviceSign->getSign($data);
            }
            else{
                $sign = $serviceSign->getSign($data, $this->key);
            }
            $data['sign'] = $sign;
        }
        $data = http_build_query($data);
        return $data;
    }

    public function setMethod($method = 'get')
    {
        $this->method = $method;
        return $this;
    }

    public function setSignAppKey($key = '')
    {
        $this->key = $key;
        return $this;
    }

    public function setSign($sign = 1)
    {
        $this->sign = $sign;
        return $this;
    }

    public function setDomain($domain = '')
    {
        $this->domain = $domain;
        return $this;
    }

    public function setPath($path = 'Api/Feedback/getType')
    {
        $this->path = $path;
        return $this;
    }

    public function setData($data = [])
    {
        $this->data = $data;
        return $this;
    }

    public function getResponse()
    {
        $domain = $this->domain;
        if(empty($domain)){
            $domain = getDomain();
        }
        $path = $this->path;
        $path = ltrim($path, '/');
        $path = rtrim($path, '/');
        $url = "{$domain}/{$path}";
        if($this->method == 'get'){
            return $this->sendGetByCurl($url, $this->data);
        }
        return $this->sendPostByCurl($url, $this->data);
    }

    public function print_r_ln($data)
    {
        print_r($data);
        echo PHP_EOL;
    }

}